# -*- coding: utf-8 -*-
from flask import Flask, jsonify
from flask_restful import Resource, Api, reqparse
import redis
import random
import string
import time
import pymysql,requests
from lxml import etree

app = Flask(__name__)
api = Api(app)

pool = redis.Redis(host='localhost', port=6379)




def GenNumber(length): #生成随机数
    chars=string.digits
    return ''.join([random.choice(chars) for i in range(length)])

class Lianlianpay(): #连连支付
    def __init__(self):
        self.session = requests.session()
        self.headers = {'Cookie':'JSESSIONID=771C5A41EC1E2E0EAF76697FC0925051; redisid=677811D140224B015EAD7B2B503AAFC6',}


    def recharge(self,phone,money):
        recharge = 'http://www.aikaixin.com/topup/recharge.do'
        data = {
            'hidispid':None,
            'hidareacode':None,
            'custTime':time.strftime("%Y%m%d-%H%M%S", time.localtime()),
            'ctimestamp':time.time(),
            'custcode':phone,
            'faceMoney':money,
            'paypassword':'060716',
            'goodsValue':'0%7C%7C68%7C102337%7C102337%7CSCDXM001%7C1%7C10%7C2000%7C.9972%7C29%7C04',
            'payMethods':'0',
            'ntpwd':'0'
        }
        self.session.post(recharge, data = data, headers = self.headers)


    def query(self,phone):
        query_url = 'http://www.aikaixin.com/topupOrder/orderList.do'
        data = {
            'nowPage': '1',
            'begin': '1',
            'num': '10',
            'status': None,
            'ispid': None,
            'loginname': None,
            'begindate': time.strftime("%Y-%m-%d", time.localtime()),
            'enddate': time.strftime("%Y-%m-%d", time.localtime()),
            'custcode': phone,
        }

        r = requests.post(query_url,data = data,headers = headers)
        html = etree.HTML(r.text)
        create_time = html.xpath('//*[@id="searchForm"]/div/div/div/table/tbody/tr/td[1]')
        order_id = html.xpath('//*[@id="searchForm"]/div/div/div/table/tbody/tr/td[2]')
        number = html.xpath('//*[@id="searchForm"]/div/div/div/table/tbody/tr/td[3]')
        result = html.xpath('//*[@id="searchForm"]/div/div/div/table/tbody/tr/td[7]/span')
        money = html.xpath('//*[@id="searchForm"]/div/div/div/table/tbody/tr/td[5]')
        result_list = []
        for a,b,c,d,e in zip(order_id,number,result,money,create_time):
            query_list = {
                'order_id':''.join(a.text.split()),
                'number':b.text,
                'result':c.text,
                'money':d.text,
                'create_time':str(e.text).encode('utf-8'),
            }
            result_list.append(query_list)
        return result_list


class Commit(Resource): #提交新号码
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('phone_number', type=int, required=True)
        parser.add_argument('money', type=int, required=True)
        args = parser.parse_args()
        if len(str(args['phone_number'])) !=11:
            result = {
                "messages":'Error phone_number length'
            }
        else:
            result = {
                "phone_number": args["phone_number"],
                "money": args["money"],
                "ID": time.strftime("%Y%m%d%H%M%S", time.localtime())+GenNumber(10),
                "stat":'success'
            }

            pool.rpush('yaohang',result)

            sql = '''INSERT INTO post(id,phone_number,money) VALUES (%s,%s,%s)''' % (result['ID'],result['phone_number'],result['money'])
            db = pymysql.connect('localhost', 'root', 'qweasdzxc', 'test', charset='utf8')
            cursor = db.cursor()
            cursor.execute(sql)
            db.commit()
            db.close()
        return jsonify(result)

class query(Resource):

    def get(self):
        db = pymysql.connect('localhost', 'root', 'qweasdzxc', 'test', charset='utf8',
                             cursorclass=pymysql.cursors.DictCursor)
        cursor = db.cursor()
        parser = reqparse.RequestParser()
        parser.add_argument('ID', type=int, required=True)
        args = parser.parse_args()
        sql = "SELECT * FROM Recharge_record WHERE order_id = %s" % args['ID']

        try:
            cursor.execute(sql)
            results = cursor.fetchall()
            if len(results) == 0:
                result = {
                    "error": 'No query to the corresponding ID, please try again later'
                }
                return jsonify(result)

            else:
                for i in results:
                    result = {
                        "phone_number": i['phone_number'],
                        "money": i['money'],
                        'result': i['result'],
                        'mobile_order_id': i['mobile_order_id'],
                    }
                    return jsonify(result)


        except:
            print 'error'
        db.close()





api.add_resource(Commit, '/')
api.add_resource(query, '/query')

if __name__ == '__main__':
    app.run(host='0.0.0.0',port=50000, debug=True)
